package com.strelitzia.email.impl;

import com.strelitzia.constant.EmailConstant;
import com.strelitzia.email.EmailService;

import com.strelitzia.exception.StrelitziaException;
import com.strelitzia.utils.EmailUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;
import java.util.concurrent.TimeUnit;

/**
 * @create 2023/12/14 11:44
 */
@Service
@Slf4j
public class EmailServiceImpl implements EmailService {
    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * html邮件
     *
     * @param to      收件人
     * @param subject 主题
     * @param code    验证码
     */
    @Override
    public void sendMail(String to, String subject, String code) throws StrelitziaException {
        //获取MimeMessage对象
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper messageHelper;
        try {
            messageHelper = new MimeMessageHelper(message, true);
            //邮件发送人
            messageHelper.setFrom(EmailConstant.EMAIL_FROM);
            //邮件接收人
            messageHelper.setTo(to);
            //邮件主题
            message.setSubject(subject);
            //邮件内容，html格式
            messageHelper.setText(EmailUtil.getEmailContent(code), true);
            //发送
            mailSender.send(message);
            redisTemplate.opsForValue().set(to, code, 180, TimeUnit.SECONDS);
            log.info("邮件发送成功");
        } catch (Exception e) {
            log.error("邮件发送异常");
            throw new StrelitziaException("邮件发送异常");
        }
    }
}
